﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NovelReader
{
    public class SqliteNovelManage
    {
        private NovelDBEntities dbNovelEntities;

        public SqliteNovelManage()
        {
            dbNovelEntities = new NovelDBEntities();
        }

        /// <summary>
        /// 通过XML文件记录小说的信息
        /// 
        /// 操作完成之后会生成一个XML文件，通过读取XML文件中IsUpdated
        /// 就可以知道哪些链接已经更新到最新了
        /// </summary>
        /// <param name="novel">小说信息。这是一个结构体</param>
        /// <returns></returns>
        public bool CheckNovelFromSqlite(Novel novel)
        {
            long chapterID = -1;
            long novelID = -1;
            long linkID = -1;

            // 判断是否存在同名小说。如果存在，则不去添加小说
            novelID = (from nT in dbNovelEntities.TNovels
                       where nT.Name == novel.NovelName
                       select nT.ID).FirstOrDefault();
            if (novelID == 0)
            {
                // 出现以外的话, 就表示前面没有这个记录
                TNovel n = dbNovelEntities.TNovels.CreateObject();
                n.Name = novel.NovelName;
                n.Memo = novel.NovelDescription;
                n.ID = dbNovelEntities.TNovels.Max(x => x.ID) + 1;

                dbNovelEntities.TNovels.AddObject(n);
                novelID = n.ID;
            }

            // 更新小说章节。如果不存在对应名称的章节，就创建
            foreach (NovelChapter chap in novel)
            {

                chapterID = (from n in dbNovelEntities.TNovelChapters
                             where n.ChapterName == chap.ChapterName
                             select n.ID).FirstOrDefault();

                if (chapterID == 0)
                {
                    TNovelChapter c = dbNovelEntities.TNovelChapters.CreateObject();
                    c.ID = dbNovelEntities.TNovelChapters.Max(x => x.ID) + 1;
                    c.NovelID = novelID;
                    c.ChapterName = chap.ChapterName;
                }

                // 更新章节内目录
                foreach (NovelLink link in chap)
                {

                    linkID = (from n in dbNovelEntities.TNovelLinks
                              where n.ChapterID == chapterID && n.LinkName == link.Title
                              select n.ID).FirstOrDefault();

                    if (linkID == 0)
                    {
                        TNovelLink l = dbNovelEntities.TNovelLinks.CreateObject();
                        l.Description = link.Description;
                        l.ChapterID = chapterID;
                        l.LinkHref = link.Href;
                        l.LinkName = link.Title;
                        l.ID = dbNovelEntities.TNovelLinks.Max(x => x.ID) + 1;
                    }
                }
            }

            dbNovelEntities.SaveChanges();

            return true;
        }
    }
}
